package com.czy.utilslib;

import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.content.Intent;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class BaseApplication extends Application {

    //------------------------------instance------------------------------

    protected BaseApplication(){
        super();
    }

    protected static BaseApplication sInstance;

    public static BaseApplication getInstance(){
        if (sInstance == null){
            sInstance = new BaseApplication();
        }
        return sInstance;
    }

    //------------------------------Activity / Fragment------------------------------

    public List<String> activityList;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        activityList = new LinkedList<>();
        initActivityMap();
    }

    private Map<String, Activity> activityMap;  //需要管理的Activity
    private Map<String, Fragment> fragmentMap;  //需要管理的Fragment

    private void initActivityMap(){
        activityMap = new HashMap<>();
        fragmentMap = new HashMap<>();
    }

    public Activity getActivityByName(String name){
        return activityMap.get(name);
    }

    public Fragment getFragmentByName(String name){
        return fragmentMap.get(name);
    }

    public void addActivity(String name, Activity activity){
        activityMap.put(name,activity);
    }

    public void clearActivityInMap(String name){
        activityMap.remove(name);
    }

    public void closeActivity(String name){
        if(activityMap.get(name) != null){
            activityMap.get(name).finish();
        }
        activityMap.remove(name);
    }

    // 跳转到指定的Activity并且清除其他Activity的缓存
    public void TurnAndFinishAllActivity(Activity start,Class<? extends Activity> targetClass,String startName,String targetName){
        for (Map.Entry<String, Activity> entry : activityMap.entrySet()) {
            String name = entry.getKey();
            Activity activity = entry.getValue();

            // 排除 startName 和 targetName 对应的 Activity
            if (!name.equals(startName) && !name.equals(targetName)) {
                activity.finish();
            }
        }
        Intent intent = new Intent(start,targetClass);
        start.startActivity(intent);
        start.finish();
    }

    //------------------------------Share Preferences------------------------------

}
